<?php
namespace app\controller;

use app\BaseController;
use app\model\DeviceData;
use app\model\Device as DeviceModel;
use think\facade\Db;

class Data extends BaseController
{
    /**
     * 获取数据统计概览
     */
    public function overview()
    {
        // 获取当天数据总量
        $todayCount = DeviceData::whereDay('data_time')->count();
        
        // 获取昨天数据总量
        $yesterdayCount = DeviceData::whereDay('data_time', 'yesterday')->count();
        
        // 获取本周数据总量
        $weekCount = DeviceData::whereWeek('data_time')->count();
        
        // 获取本月数据总量
        $monthCount = DeviceData::whereMonth('data_time')->count();
        
        // 获取总数据量
        $totalCount = DeviceData::count();
        
        // 获取告警数据总量
        $alarmCount = DeviceData::where('is_alarm', 1)->count();
        
        // 告警率
        $alarmRate = $totalCount > 0 ? round(($alarmCount / $totalCount) * 100, 2) : 0;
        
        return $this->success('获取成功', [
            'today_count' => $todayCount,
            'yesterday_count' => $yesterdayCount,
            'week_count' => $weekCount,
            'month_count' => $monthCount,
            'total_count' => $totalCount,
            'alarm_count' => $alarmCount,
            'alarm_rate' => $alarmRate
        ]);
    }
    
    /**
     * 获取数据类型分布
     */
    public function typeDistribution()
    {
        // 获取所有数据类型分布
        $distribution = DeviceData::field('data_type, COUNT(*) as count')
            ->group('data_type')
            ->select();
        
        return $this->success('获取成功', $distribution);
    }
    
    /**
     * 获取数据趋势
     */
    public function trend()
    {
        // 获取请求参数
        $params = $this->request->get();
        $timeRange = $params['time_range'] ?? 'day';
        $dataType = $params['data_type'] ?? '';
        $deviceId = $params['device_id'] ?? '';
        
        // 构建基础查询
        $query = DeviceData::order('data_time', 'asc');
        
        // 筛选数据类型
        if (!empty($dataType)) {
            $query = $query->where('data_type', $dataType);
        }
        
        // 筛选设备ID
        if (!empty($deviceId)) {
            $query = $query->where('device_id', $deviceId);
        }
        
        // 按照时间范围查询
        switch ($timeRange) {
            case 'hour':
                // 最近24小时，按小时分组
                $query = $query->whereTime('data_time', '-24 hours');
                $groupFormat = '%Y-%m-%d %H:00:00';
                break;
            case 'day':
                // 最近30天，按天分组
                $query = $query->whereTime('data_time', '-30 days');
                $groupFormat = '%Y-%m-%d';
                break;
            case 'week':
                // 最近12周，按周分组
                $query = $query->whereTime('data_time', '-84 days');
                $groupFormat = '%Y-%u';
                break;
            case 'month':
                // 最近12个月，按月分组
                $query = $query->whereTime('data_time', '-12 months');
                $groupFormat = '%Y-%m';
                break;
            default:
                // 默认最近30天，按天分组
                $query = $query->whereTime('data_time', '-30 days');
                $groupFormat = '%Y-%m-%d';
        }
        
        // 获取数据，按时间分组聚合
        $trend = $query->field([
            "DATE_FORMAT(data_time, '{$groupFormat}') as time_point",
            'COUNT(*) as count',
            'AVG(data_value) as avg_value',
            'MAX(data_value) as max_value',
            'MIN(data_value) as min_value',
            'SUM(is_alarm) as alarm_count'
        ])
        ->group('time_point')
        ->select();
        
        return $this->success('获取成功', $trend);
    }
    
    /**
     * 获取设备数据排行
     */
    public function deviceRanking()
    {
        // 获取请求参数
        $params = $this->request->get();
        $limit = $params['limit'] ?? 10;
        $orderBy = $params['order_by'] ?? 'count';
        
        // 获取设备数据排行
        $ranking = Db::name('device_data')
            ->alias('d')
            ->join('device dev', 'd.device_id = dev.id')
            ->field([
                'dev.id',
                'dev.name',
                'dev.serial_no',
                'COUNT(*) as count',
                'SUM(CASE WHEN d.is_alarm = 1 THEN 1 ELSE 0 END) as alarm_count'
            ])
            ->group('d.device_id')
            ->order($orderBy, 'desc')
            ->limit($limit)
            ->select();
        
        return $this->success('获取成功', $ranking);
    }
    
    /**
     * 获取数据质量分析
     */
    public function qualityAnalysis()
    {
        // 获取请求参数
        $params = $this->request->get();
        $startTime = $params['start_time'] ?? '';
        $endTime = $params['end_time'] ?? '';
        
        // 构建查询
        $query = DeviceData::alias('d');
        
        // 按时间范围筛选
        if (!empty($startTime) && !empty($endTime)) {
            $query = $query->whereBetweenTime('data_time', $startTime, $endTime);
        }
        
        // 统计数据总量
        $totalCount = $query->count();
        
        // 统计有效数据量（非零、非空、在合理范围内）
        $validCount = $query->where('data_value', '<>', '')
            ->where('data_value', '<>', '0')
            ->count();
        
        // 计算数据完整率
        $integrityRate = $totalCount > 0 ? round(($validCount / $totalCount) * 100, 2) : 0;
        
        // 统计告警数据
        $alarmCount = $query->where('is_alarm', 1)->count();
        
        // 计算告警率
        $alarmRate = $totalCount > 0 ? round(($alarmCount / $totalCount) * 100, 2) : 0;
        
        // 按告警类型统计
        $alarmTypes = $query->where('is_alarm', 1)
            ->field('alarm_type, COUNT(*) as count')
            ->group('alarm_type')
            ->select();
        
        return $this->success('获取成功', [
            'total_count' => $totalCount,
            'valid_count' => $validCount,
            'integrity_rate' => $integrityRate,
            'alarm_count' => $alarmCount,
            'alarm_rate' => $alarmRate,
            'alarm_types' => $alarmTypes
        ]);
    }
} 